package util.core.plugins.mycraft.cc;

import implate.core.plugins.mycraft.cc.DBConnImplate;
import implate.core.plugins.mycraft.cc.Mycraft;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.bukkit.craftbukkit.libs.jline.internal.Log;

import entity.core.plugins.mycraft.cc.config;
import entity.core.plugins.mycraft.cc.SqlLink;
import entity.core.plugins.mycraft.cc.db;

public class DBConn extends Mycraft implements DBConnImplate {
	private SqlLink sql;
	private db db;

	public DBConn() {
		this.sql = null;
	}
	
	public DBConn(config cf) {
		if(cf.isNull == false) {
			this.G_cf = cf;
			this.db = cf.getDb();
		}
		if(this.db.getHost().isEmpty())
			this.db = null;
		if((int)this.db.getPort() < 1)
			this.db = null;
		if(this.db.getPwd().isEmpty())
			this.db = null;
		if(this.db.getUser().isEmpty())
			this.db = null;
		if(this.db.getDbs().isEmpty())
			this.db = null;
		this.GetCon();
	}
	@Override
	public void GetCon() {
		// TODO Auto-generated method stub
		if(this.db != null) {
			if(this.db.getType().equals("mysql")) {
				String linkUrl = "jdbc:mysql://" +
						this.db.getHost().toString() +
						":" + this.db.getPort() +
						"/" + this.db.getDbs().toString() +
						this.db.getUrl().toString();
				if(this.G_cf.getDebug() == 1) {
					Log.info("[debug] MycraftPluginCore: DBConn -> GetCon(): SQL CONNECT => "+linkUrl);
				}
				try {
					Class.forName("com.mysql.jdbc.Driver");
					this.sql = new SqlLink(DriverManager.getConnection(linkUrl, 
                            this.db.getUser().toString(), 
                            this.db.getPwd().toString()));
				} catch(Exception e) {
				    Log.error("SQL Connect Fail! ",e.getMessage());
				}
			}
		}
	}
	@Override
	public void CloseCon() {
		// TODO Auto-generated method stub
		try {
			this.sql.getLink().close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public SqlLink getSql() {
		return sql;
	}
	public void setSql(SqlLink sql) {
		this.sql = sql;
	}
	public db getDb() {
		return db;
	}
	public void setDb(db db) {
		this.db = db;
	}

}
